/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.powerhua.xsys.workflow.web;

import com.powerhua.core.utils.FileContentUtils;
import com.powerhua.core.utils.PathUtils;
import com.powerhua.core.web.IServletAction;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author yanyi.xu
 */
public class WorkflowMainPageAction implements IServletAction {

    private static String MODEL = "workflow";
    private static String[] MAIN_CONTENTS = new String[]{
        "index_content/WorkflowDefs", "index_content/WorkflowTasks",
        "index_content/WorkflowContents",
        "index_content/WorkflowImages", "index_content/WorkflowForms"
    };

    @Override
    public String doAction(HttpServletRequest request) {

        String action = request.getParameter("act");

        if ("main".equals(action)) {
            return getMainPageContent();
        } else if ("deploy".equals(action)) {
            String[] workflowPages = new String[]{
                "index_content/WorkflowDefUpload"
            };
            return getPageContent(workflowPages);
        } else {
            return "";
        }
    }

    /**
     * 
     * @return
     */
    private String getMainPageContent() {
        StringBuffer result = new StringBuffer("");
        String path = getWebContentPath();
        String pathTmp = path + MODEL + "/index.html";
        String content = FileContentUtils.getTextFileString(pathTmp, "UTF-8");

        /*
         * 内容
         */
        String compStr = getPageContent(MAIN_CONTENTS);

        /*
         * 替换
         */
        result.append(content.replaceFirst("\\<!-- replace with content -->", compStr));
        return result.toString();
    }

    /**
     * 
     * @param workflowPages
     * @return
     */
    private String getPageContent(String[] contents) {
        StringBuffer result = new StringBuffer("");
        String path = getWebContentPath();

        for (int i = 0; i < contents.length; i++) {
            String pathTmp = path + MODEL + "/" + contents[i] + ".html";
            String content = FileContentUtils.getTextFileString(pathTmp, "UTF-8");
            int start = content.indexOf("<body>");
            int end = content.indexOf("</body>");
            content = content.substring(start + 6, end);
            result.append(content);
        }

        return result.toString();
    }

    /**
     * 
     * @return
     */
    private String getWebContentPath() {
        String fullPath = PathUtils.getClassBasePath();
        String path = "";

        if (fullPath.indexOf(".jar!") > 0) {
            int i = fullPath.indexOf("/WEB-INF/lib/");
            path = fullPath.substring(0, i + 1);
        } else {
            int i = fullPath.indexOf("/WEB-INF/classes/");
            path = fullPath.substring(0, i + 1);
        }

        return path;
    }
}
